package com.nafets;

import com.nafets.util.MathUtils;


public class GuitarString {
	private Tone startTone;
	private LineCoef lineCoef;
	private int frets;
	private int[] fretTones;
	private double x1, y1, x2, y2;

	public GuitarString(double x1, double y1, double x2, double y2, Tone startTone, int frets) {
		this.x1 = x1;
		this.y1 = y1;
		this.x2 = x2;
		this.y2 = y2;
		this.frets = frets;
		this.startTone = startTone;
		this.lineCoef = MathUtils.getLineCoefficients(x1, y1, x2, y2);
		initTones(startTone, frets);
	}

	private void initTones(Tone tone, int frets) {
		fretTones = new int[frets + 1];

		int currentTone = tone.getToneValue();
		fretTones[0] = currentTone++;
		for (int i = 1; i <= frets; i++, currentTone++) {
			if (currentTone > Tone.B.getToneValue()) {
				currentTone = Tone.C.getToneValue();
			}
			fretTones[i] = currentTone;
		}
	}

	public int getToneAt(int i) {
		if (i < 0 || i > frets) {
			throw new IllegalArgumentException(String.format(
					"Invalid argument [%d]. Ask for a fret between [0] and [%d]", i, frets));
		}

		return fretTones[i];
	}

	public Tone getStartTone() {
		return startTone;
	}

	public double getX1() {
		return x1;
	}

	public double getY1() {
		return y1;
	}

	public double getX2() {
		return x2;
	}

	public double getY2() {
		return y2;
	}

	public LineCoef getLineCoef() {
		return lineCoef;
	}
	
	public double distanceTo(double x, double y) {
		return MathUtils.distanceFromLine(x, y, x1, y1, x2, y2, lineCoef.a, lineCoef.b);
	}
}
